using System;
using System.Collections.Generic;
using QFramework;
using UnityEngine;

namespace Survivor
{
    public class CoinUpgradeSystem : AbstractSystem,ICanSave
    {
        public List<CoinUpgradeItem> Items = new List<CoinUpgradeItem>();
        public Action OnCoinUpgradeSystemChanged = null;
        
        protected override void OnInit()
        {
            Items.Add(new CoinUpgradeItem()
            {
                Key = "coin_gain_value",
                Description = "Boost Coin Gain Value",
                Level = 0,
                MaxLevel = 3,
                GetPriceByLevel = (level)=> (level + 1) * 5,
                OnUpgrade = (self) =>
                {
                    if (Global.Coin.Value >= self.Price)
                    {
                        Global.CoinGainValue.Value += 1;
                        Global.Coin.Value -= self.Price;
                    }
                }
            });
            
            Items.Add(new CoinUpgradeItem()
            {
                Key = "exp_gain_value",
                Description = "Boost Exp Gain Value",
                Level = 0,
                MaxLevel = 3,
                GetPriceByLevel = (level)=> (level + 1) * 10,
                OnUpgrade = (self) =>
                {
                    if (Global.Coin.Value >= self.Price)
                    {
                        Global.ExpGainValue.Value += 1;
                        Global.Coin.Value -= self.Price;
                    }
                }
            });
            
            Items.Add(new CoinUpgradeItem()
            {
                Key = "increase_max_hp",
                GetPriceByLevel = (level)=> (level + 1) * 20,
                Description = "Increase Max Hp",
                Level = 0,
                MaxLevel = 5,
                OnUpgrade = (self) =>
                {
                    if (Global.Coin.Value >= self.Price)
                    {
                        Global.MaxHp.Value += 1;
                        Global.Coin.Value -= self.Price;
                    }
                }
            });

            foreach (var item in Items)
            {
                item.OnUpgrade += (self) => { OnCoinUpgradeSystemChanged?.Invoke(); };
            }

            OnCoinUpgradeSystemChanged += Save;
            
            Load();

        }

        public void Save()
        {
            var saveSystem = this.GetSystem<SaveSystem>();
            foreach (var item in Items)
            {
                saveSystem.SetInt(item.Key,item.Level);
            }
        }

        public void Load()
        {
            var saveSystem = this.GetSystem<SaveSystem>();
            foreach (var item in Items)
            {
                item.Level = saveSystem.GetInt(item.Key);
            }
        }
    }
}
